package cn.yunbamboos.bean;

import cn.hutool.core.util.ObjUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ObjectUtils;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolDynamicTaskExecutor implements DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolDynamicTaskExecutor.class);

    private final Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>();
    private final Map<String, Runnable> runnableMap = new ConcurrentHashMap<>();

    private final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;

    public ThreadPoolDynamicTaskExecutor(int corePoolSize, String namePrefix) {
        this.scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(corePoolSize);
        this.scheduledThreadPoolExecutor.setRemoveOnCancelPolicy(true);
        // 当是true时，在执行shutdown方法后，当前正在等待的任务的和正在运行的任务需要被执行完，然后进程被销毁
        this.scheduledThreadPoolExecutor.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
        // 当是true时，在cheduleAtFisedRate方法和scheduleWithFixedDelay方法提交的任务会继续循环执行
        this.scheduledThreadPoolExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(true);
        this.scheduledThreadPoolExecutor.setThreadFactory(new CustomThreadFactory(namePrefix));
    }

    /**
     * 循环执行的任务
     *
     * @param key          任务ID
     * @param task         任务
     * @param initialDelay 任务
     * @param period       间隔 毫秒
     */
    public void startCron(String key, Runnable task, long initialDelay, long period, TimeUnit unit) {
        if (ObjectUtils.isEmpty(key)) {
            return;
        }
        ScheduledFuture<?> future = futureMap.get(key);
        if (future != null) {
            if (future.isCancelled()) {
                logger.debug("任务【{}】已存在但是关闭状态！！！", key);
            } else {
                logger.debug("任务【{}】已存在且已启动！！！", key);
                return;
            }
        }
        future = scheduledThreadPoolExecutor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS);
        if (ObjUtil.isNotNull(future)) {
            futureMap.put(key, future);
            runnableMap.put(key, task);
            logger.debug("任务【{}】启动成功！！！", key);
        } else {
            logger.debug("任务【{}】启动失败！！！", key);
        }
    }

    /**
     * 延时任务
     *
     * @param key   任务ID
     * @param task  任务
     * @param delay 延时 /毫秒
     */
    public void startDelay(String key, Runnable task, int delay) {
        this.startDelay(key, task, delay, TimeUnit.MILLISECONDS);
    }

    /**
     * 延时任务
     *
     * @param key   任务ID
     * @param task  任务
     * @param delay 延时 /毫秒
     * @param unit  时间类型
     */
    public void startDelay(String key, Runnable task, int delay, TimeUnit unit) {
        if (ObjectUtils.isEmpty(key)) {
            return;
        }
        stop(key);
        ScheduledFuture<?> future = futureMap.get(key);
        if (future != null) {
            if (future.isCancelled()) {
                logger.debug("任务【{}】已存在但是关闭状态！！！", key);
            } else {
                logger.debug("任务【{}】已存在且已启动！！！", key);
                return;
            }
        }
        future = scheduledThreadPoolExecutor.schedule(task, delay, unit);
        if (ObjUtil.isNotNull(future)) {
            futureMap.put(key, future);
            runnableMap.put(key, task);
            logger.debug("任务【{}】启动成功！！！", key);
        } else {
            logger.debug("任务【{}】启动失败！！！", key);
        }
    }

    public boolean stop(String key) {
        if (ObjectUtils.isEmpty(key)) {
            return false;
        }
        boolean result = false;
        if (!ObjectUtils.isEmpty(futureMap.get(key)) && !futureMap.get(key).isCancelled() && !futureMap.get(key).isDone()) {
            result = futureMap.get(key).cancel(false);
            futureMap.remove(key);
            runnableMap.remove(key);
        }
        return result;
    }

    public boolean contains(String key) {
        if (ObjectUtils.isEmpty(key)) {
            return false;
        }
        return futureMap.get(key) != null;
    }

    public Set<String> getAllKeys() {
        return futureMap.keySet();
    }

    public Runnable get(String key) {
        if (ObjectUtils.isEmpty(key)) {
            return null;
        }
        return runnableMap.get(key);
    }

    /**
     * 每五分钟检查失效的任务，并移除
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void execute() {
        if (!futureMap.isEmpty()) {
            for (String key : futureMap.keySet()) {
                ScheduledFuture<?> future = futureMap.get(key);
                if (future.isDone() || future.isCancelled()) {
                    futureMap.remove(key);
                    runnableMap.remove(key);
                }
            }
        }
    }

    public boolean isAlive(String key) {
        return futureMap.get(key) != null && !futureMap.get(key).isDone() && !futureMap.get(key).isCancelled();
    }

    @Override
    public void destroy() throws Exception {
        Set<String> keys = getAllKeys();
        for (String key : keys) {
            if (stop(key)) {
                logger.info("[程序停止] 销毁任务 {}", key);
            } else {
                logger.info("[程序停止] 销毁任务失败 {}", key);
            }
        }
        scheduledThreadPoolExecutor.shutdown();
    }
}
